/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution
{
public:
    ListNode *removeNthFromEnd(ListNode *head, int n)
    {
        ListNode *fast = head;
        ListNode *slow = head;
        ListNode slowPrevNode = ListNode(0, head);
        ListNode *slowPrev = &slowPrevNode;
        for (int i = 0; i < n; ++i)
        {
            fast = fast->next;
        }
        while (fast != nullptr)
        {
            fast = fast->next;
            slow = slow->next;
            slowPrev = slowPrev->next;
        }
        if (slow == head)
        {
            ListNode *result = head->next;
            delete head;
            return result;
        }
        slowPrev->next = slow->next;
        delete slow;
        return head;
    }
};